package com.study.jvm.reference;

import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

/**
 * -Xmx20m -XX:+PrintGCDetails -verbose:gc
 */
public class SoftReferenceGc {
    private static final int _4MB = 1024 * 1024 * 4;

    public static void main(String[] args) {
//        strongReference();
        softReference();
    }

    private static void strongReference() {

        List<byte[]> bytes = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            byte[] e = new byte[_4MB];
            bytes.add(e);
            System.out.println(e);
        }
        System.out.println("\n");
        for (byte[] e : bytes) {
            System.out.println(e);
        }
    }

    private static void softReference() {

        List<SoftReference<byte[]>> bytes = new ArrayList<>();
        ReferenceQueue<byte[]> referenceQueue = new ReferenceQueue<>();
        for (int i = 0; i < 5; i++) {
            //关联了引用队列，gc后会把软引用放入引用队列中
            SoftReference<byte[]> e = new SoftReference(new byte[_4MB],referenceQueue);
            bytes.add(e);
            System.out.println(e.get());
        }

        Reference<? extends byte[]> poll = referenceQueue.poll();
        while (poll != null) {
            bytes.remove(poll);
            poll = referenceQueue.poll();
        }
        System.gc();
        System.out.println("---------------------- ");
        for (SoftReference<byte[]> e : bytes) {
            System.out.println(e.get());
        }
    }
}
